import {message} from "antd";
import React, {memo, MouseEvent, useState, Dispatch, useEffect, useCallback} from 'react';
import { useParams } from "react-router-dom";
import { isDevelopment, assign, getStore, setStore, removeStore } from '@bastet/utils';
import { IComponentType } from '@bastet/widgets';
import type { IComponent } from '@bastet/widgets';
import { BuilderInformation, BuilderWidgetPanel, BuilderEditor, Context } from '../../../builder';
import {  } from '../../../builder';
import { useScene, useWidgets, useSyncCallback, useStateReducer } from '../../../hooks';
import { widgets as testWidgetNames } from '../../../widgets.json';

console.log('testWidgetNames: => ', testWidgetNames)
const localWidgetObject: Map<string, Promise<any>> = (import.meta as any).glob('/src/widget/**/index.tsx');
console.log('importAsync: => ', localWidgetObject);


function getInformation (state: any, path?: string) {
  if (path) {
    const pathArr = path.split('-');
    let data = null;
    while (pathArr.length) {
      const path: string = pathArr.shift() as string
      if (!data) {
        data = state[path]
      } else {
        data = data[path]
      }
    }
    console.log('getInformation => ', data, path)
    return data;
  }
}

// console.log(originalState)
export default memo(() => {
  const [debugging, setDebugging ] = useState<any>(getStore('debugging'))
  const params = useParams<{id: string}>();
  const [ state, dispatch, changeField ] = useStateReducer()
  const [ scene, getSceneById, updateScene ] = useScene()
  const widgets = useWidgets(debugging)
  const [ activated, setActivePath ] = useState<string>()
  // const [ information, setInformation ] = useInformationReducer<IComponent>(state as IComponent[])
  const information = getInformation(state as IComponent[], activated)
  const __onClick = (_event: MouseEvent <Element>, data: IComponent) => {
    console.log('BuilderLayout: ——————————————__onClick => ', data, information?.path)
    setActivePath(data.id)
  }

  useEffect(() => {
    if (!params?.id) return;

    getSceneById(params.id, debugging).then(() => {

    })
  }, [params.id, debugging])

  useEffect(() => {
    if (params?.id) return;
    // const remoteWidgets = debugWidgets(widgets, debugging)
    // const sceneWidgets = mergeWidget(scene.data.widgets, remoteWidgets)
    // console.log('sceneWidgets', scene.data.widgets, sceneWidgets)
    // dispatch(sceneWidgets)
  }, [debugging])

  const onSave = useSyncCallback(() => {
    updateScene(state)/*.then(({code, msg}) => {
      if (code === 200) message.info(msg)
    })*/
  })

  const onCancel = () => {

  }
  const onDevelop = () => {
    if (debugging) {
      removeStore('debugging')
      setDebugging('')
    } else {
      setDebugging('debug')
      setStore('debugging', 'debug')
    }
  }

  console.log(';;;;;;;;;;;;; => ', (import.meta as any).env.DEV, `debugging: => ${ debugging }`);
  // console.log('originalState: => ', state)
  console.log(`%cinit page data: => `, 'background: #8ce196;', { activated, information, scene, state, widgets});
  console.log(`%cinit page data: => `, 'background: #8ce196;', [...state.values()]);
  return (
      <div className="root-builder">
        <BuilderWidgetPanel widgets={widgets} />
        <Context.Provider value={debugging}>
          {
            scene?.widgets && (
              <BuilderEditor
                defaultStyle={{ width: `calc(100vw - ${!information?.path ? 100 : 420}px)` }}
                state={scene?.widgets}
                activated={activated}
                dispatch={dispatch as Dispatch<any>}
                changeField={changeField as Dispatch<any>}
                widgets={widgets}
                onClick={__onClick}
                onSave={onSave}
                onCancel={onCancel}
                onDevelop={onDevelop}
              />
            )
          }
        </Context.Provider >
        {
            information?.path && (
                <BuilderInformation
                    information={information}
                    dispatch={changeField as Dispatch<any>}/>
            )
        }
      </div>
  )
})
